<?php
/*
Plugin Name: Import Blogroll With Categories & Google Alert Creation
Plugin URI: http://wordpress.org/extend/plugins/import-blogroll-with-categories/
Description: Import links/blogroll in OPML format and allow them to be inserted into their proper link categories. Also allow creation of Google alerts as links.
Version: 2.0 
Author: Alan Whipple & Mark Tilly
Author URI: http://www.target-info.com
*/

/*  Copyright 2009  Alan Whipple  (email: lordalan@gmail.com)
     
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
//Modified to Add Google Alert creation and storage as a link
//Modified google alerts api (GoogleAlertService.php) to use ../ as path for the license key so it looks in plugin directory
//V2.0
//Modified to create a google news feed, and support creation of one from a new topic

$add_import_link_to_links_menu = true; // Set this to 'false' if you don't want to add 'Import' to the Links sub-menu
$add_export_link_to_links_menu = true; // Set this to 'false' if you don't want to add 'Export' to the Links sub-menu

function set_bwc_opml(){
	register_importer('bwc_opml', __('Blogroll With Categories'), __('Import links in OPML format into their proper <strong>link categories</strong>.'), array(&$opml_importer, 'dispatch'));
	if (isset($_GET['import']) && $_GET['import']=='bwc_opml' ) {
		//include(ABSPATH . "wp-content/mu-plugins/import-blogroll-with-categories/bwc_opml.php");
		include('bwc_opml.php');
	}
}
add_action('admin_init','set_bwc_opml');

function bwc_redirect_import(){
	if ( strpos($_SERVER['REQUEST_URI'], "link-manager.php?page=import.php") ){
		wp_redirect("admin.php?import=bwc_opml");
	}
}
add_action('admin_init','bwc_redirect_import');

function bwc_add_redirect_import(){
	add_links_page('Import with categories', 'Import', 8, 'import.php', 'bwc_redirect_import');
	//add_links_page('Import with categories', 'Import', 8, 'admin.php?import=bwc_opml', ''); // Doesn't highlight "Import" in Links sub-menu
}
if ($add_import_link_to_links_menu) add_action('admin_menu', 'bwc_add_redirect_import');

function bwc_add_link_to_export(){
	add_links_page('Export Links', 'Export', 8, '../wp-links-opml.php', ''); // add a link straight to the export OPML file
}
if ($add_export_link_to_links_menu) add_action('admin_menu', 'bwc_add_link_to_export');

//
//MOD - Everything below is added for the Google Alert link creation
//

//require_once('GoogleAlertService.php'); //Add google alert service api

//Add the Create Alerts menu item
function bwc_add_link_alerts(){
    //add_links_page('Create Alerts', 'Alerts', 8, 'bwc_create_alert', 'bwc_create_alert'); // Google Alert
    add_links_page('Create News Feed', 'News or Twitter', 8, 'bwc_create_news', 'bwc_create_news');// Google News Feed
}
add_action('admin_menu', 'bwc_add_link_alerts');

//Create Alerts Screen
function bwc_create_alert(){

    $msg = '';
    //Get Link Categories for dropdown
    $cats = array (
        'orderby' => 'name',
        'hide_empty' => FALSE,
        'name' => 'link_category',
        'taxonomy' => 'link_category'
    );
    $v = array();
    
    //Handle POST
    if (isset($_POST['Submit'])){
        //Validate Fields
        $v = array (
            'username' => trim(sanitize_text_field($_POST['username'])),
            'password' => trim(sanitize_text_field($_POST['password'])),
            'aname' => trim(sanitize_text_field($_POST['aname'])),
            'keywords' => trim(stripslashes($_POST['keywords'])),
            'type' => trim(sanitize_text_field($_POST['type'])),
            'volume' => trim(sanitize_text_field($_POST['volume'])),
            'link_category' => strval(absint($_POST['link_category'])),
            'newlinkcat' => trim(sanitize_text_field($_POST['newlinkcat']))
        );
        $cats['selected'] = $v['link_category'];
        $msg = '';
        if (empty($v['username'])) $msg = bwc_add_msg($msg,'Must have a Username');
        if (empty($v['password'])) $msg = bwc_add_msg($msg,'Must have a Password');
        if (empty($v['aname'])) $msg = bwc_add_msg($msg,'Must have an Alert Name');
        if (empty($v['keywords'])) $msg = bwc_add_msg($msg,'Must have Keywords');

        if (empty($msg)) {
        //Create the new category if entered
            if (!empty($v['newlinkcat'])){
                $theterm = wp_insert_term($v['newlinkcat'],'link_category');
                if (is_wp_error($theterm)){
                    $msg = $theterm->get_error_message();
                } else {
                    $v['link_category'] = $theterm['term_id'];
                }
            }
            if (empty($msg)){
                //If OK do the creation
                $msg = bwc_do_alert_create($v);
            }
        }
        if (!empty($msg)) {
            $msgclass = 'error';
        } else {
            $msg = 'Google Alert Created';
            $msgclass = 'updated';
            $v = array();  //Don't let them recreate same one
        }
    }
    
    //Start screen page
    ?>
    <div class='wrap'>
    <?php screen_icon('link-manager'); ?>
    <h2>Create Google Alert</h2>
    <?php 
    if (!empty($msg)){ ?>
       <div id=”message” class="<?php echo $msgclass; ?>" ><p><strong><?php echo $msg ; ?></strong></p></div>
    <?php } ?>    
    <p>Use this option to create a google alert that will be placed into your links for the link category you choose.  You can then use this
        alert in any of your MyCurator Topics by including the link category as a source.</p>
    <p>Your login information will not be stored, it will only be used to create the alert.</p>
    <p><strong>All fields are required except a New Link Category</strong></p>
    <form method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI'] ); ?>"> 
        <table class="form-table" >
            <tr>
                <th scope="row">Gmail Address</th>
                <td><input name="username" type="input" id="username" size="50" maxlength="200" value="<?php echo $v['username']; ?>"/></td>    
            </tr>
            <tr>
                <th scope="row">Gmail Password</th>
                <td><input name="password" type="password" id="password" size="50" maxlength="200" value="<?php echo $v['password']; ?>" /></td>    
            </tr>
            <tr>
                <th scope="row">Alert Name</th>
                <td><input name="aname" type="input" id="aname" size="50" maxlength="200" value="<?php echo $v['aname']; ?>" /></td>    
            </tr>            
            <tr>
                <th scope="row">Alert Keywords</th>
                <td><input name="keywords" type="input" id="keywords" size="50" maxlength="200" value="<?php echo esc_attr($v['keywords']); ?>" /></td>    
            </tr>
            <tr>
                <th scope ="row">Information to Search</td>
                <td>
                    <select name="type">
                        <option value="Everything" <?php selected($v['type'],"Everything"); ?>>Everything</option>
                        <option value="Blogs" <?php selected($v['type'],"Blogs"); ?>>Blogs</option>
                        <!-- <option>Video</option> don't work with video-->
                        <option value="Discussions" <?php selected($v['type'],"Discussions"); ?>>Discussions</option>
                        <option value="News" <?php selected($v['type'],"News"); ?>>News</option>
                    </select>

                </td>
            </tr>
            <tr>
                <th scope ="row">Volume to Return</td>
                <td>
                    <select name="volume">
                        <option value="All Results" <?php selected($v['volume'],"All Results"); ?>>All Results</option>
                        <option value="Only the Best Results" <?php selected($v['volume'],"Only the Best Results"); ?>>Only the Best Results</option>
                    </select>
                </td>
            </tr>   
            <tr>
                <th scope ="row">Link Category for Alert</td>
                <td><?php wp_dropdown_categories($cats); ?></td>
            </tr> 
            <tr>
                <th scope="row">OR Enter a New Link Category</th>
                <td><input name="newlinkcat" type="input" id="newlinkcat" size="50" maxlength="200" value="<?php echo $v['newlinkcat']; ?>" /></td>    
            </tr>
       </table>
        <div class="submit">
          <input name="Submit" type="submit" value="Create Alert" class="button-primary" />
        </div>
       </form> 
    </div>    

    <?php
}

function bwc_add_msg($msg, $addmsg){
    if (empty($msg)){
        $msg = $addmsg;
    } else {
        $msg .= ' And '.$addmsg;
    }
    return $msg;
}

function bwc_do_alert_create($v){
    include_once('GoogleAlertService.php'); //Add google alert service api - move here because of conflicts with wordpress
    //Start by logging in using api object
    try {
            $service = new GoogleAlertService($v['username'], $v['password']);
        } catch (Exception $e) {
            return($e->getMessage());
        }
    
    //Get current alert id's so we can find the new one
    $cur_alerts = array();
    $alerts = $service->getAlerts();
    foreach ($alerts as $alert){
        $cur_alerts[] = $alert->getID();
    }
    
    //Create the Alert
    $type = Type::forDescription($v['type']);
    $frequency = Frequency::forDescription('As-it-happens');
    $volume = Volume::forDescription($v['volume']);
    $isFeed = true;
    $alert = new GoogleAlert($v['keywords'], $type, $frequency, $volume, $isFeed, '');
    $service->createAlert($alert);
    
    //Get Alerts now and find the new one's feed
    $alerts = $service->getAlerts();
    $newfeed = '';
    foreach ($alerts as $alert){
        if (!in_array($alert->getID(),$cur_alerts)){
            $newfeed = $alert->getFeedURL();
            break;
        }
    }
    if (empty($newfeed)) return 'Could Not Create Feed';
    $current_user = wp_get_current_user();  //Owner of this link
    //Create the new Link Record
    $linkdata = array(
 	"link_url"		=> 'http://www.google.com/alerts', // varchar, the URL the link points to
	"link_name"		=> $v['aname'], // varchar, the title of the link
	"link_visible"		=> 'Y', // varchar, Y means visible, anything else means not
	"link_owner"		=> $current_user->ID, // integer, a user ID
	"link_rss"		=> $newfeed, // varchar, a URL of an associated RSS feed
	"link_category"		=> $v['link_category'] // int, the term ID of the link category. 
    );
    $linkval = wp_insert_link( $linkdata, true );
    if (is_wp_error($linkval)){
        return $linkval->get_error_message();
    }
    return '';
}

//Create News Feed Screen
function bwc_create_news(){

    $msg = '';
    //Get Link Categories for dropdown
    $cats = array (
        'orderby' => 'name',
        'hide_empty' => FALSE,
        'name' => 'link_category',
        'taxonomy' => 'link_category'
    );
    $v = array();
    
    //Handle POST
    if (isset($_POST['Submit'])){
        //Validate Fields
        $v = array (
            'aname' => trim(sanitize_text_field($_POST['aname'])),
            'keywords' => trim(stripslashes($_POST['keywords'])),
            'link_category' => strval(absint($_POST['link_category'])),
            'newlinkcat' => trim(sanitize_text_field($_POST['newlinkcat']))
        );
        if ($_POST['ftype'] == 'G') {
            $feed_type = true;
        } else {
            $feed_type = false;
        }
        $cats['selected'] = $v['link_category'];
        $msg = '';
        if (empty($v['aname'])) $msg = bwc_add_msg($msg,'Must have a Feed Name');
        if (empty($v['keywords'])) $msg = bwc_add_msg($msg,'Must have Keywords');

        if (empty($msg)) {
        //Create the new category if entered
            if (!empty($v['newlinkcat'])){
                $theterm = wp_insert_term($v['newlinkcat'],'link_category');
                if (is_wp_error($theterm)){
                    $msg = $theterm->get_error_message();
                } else {
                    $v['link_category'] = $theterm['term_id'];
                }
            }
            if (empty($msg)){
                //If OK do the creation
                $ret = bwc_do_news_create($v,$feed_type);
                if (is_string($ret)) $msg = $ret;
            }
        }
        if (!empty($msg)) {
            $msgclass = 'error';
        } else {
            if ($feed_type) {
                $msg = 'Google News Feed Created';
            } else {
                $msg = 'Twitter Search Created';
            }
            $msgclass = 'updated';
            $v = array();  //Don't let them recreate same one
        }
    }
    
    //Start screen page
    ?>
    <div class='wrap'>
    <?php screen_icon('link-manager'); ?>
    <h2>Create Google News Feed or Twitter Search</h2>
    <?php 
    if (!empty($msg)){ ?>
       <div id=”message” class="<?php echo $msgclass; ?>" ><p><strong><?php echo $msg ; ?></strong></p></div>
    <?php } ?>    
    <p>Use this option to create a google news feed or twitter search that will be placed into your links for the link category you choose.  
        You can then use this
        feed in any of your MyCurator Topics by including the link category as a source.</p>
    <p><strong>All fields are required except a New Link Category</strong></p>
    <form method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI'] ); ?>"> 
        <table class="form-table" >
            <tr>
                <th scope="row">Google News Feed? </th>
                <td><input name="ftype" type="radio" value="G" checked /></td>
            </tr>
            <tr>
                <th scope="row">Twitter Search Feed? </th>
                <td><input name="ftype" type="radio" value="N" unchecked /></td>    
            </tr>  
            <tr>
                <th scope="row">Feed Name</th>
                <td><input name="aname" type="input" id="aname" size="50" maxlength="200" value="<?php echo $v['aname']; ?>" /></td>    
            </tr>            
            <tr>
                <th scope="row">Feed Keywords</th>
                <td><input name="keywords" type="input" id="keywords" size="50" maxlength="200" value="<?php echo esc_attr($v['keywords']); ?>" /></td>    
            </tr>
            <tr>
                <th scope ="row">Link Category for Feed</td>
                <td><?php wp_dropdown_categories($cats); ?></td>
            </tr> 
            <tr>
                <th scope="row">OR Enter a New Link Category</th>
                <td><input name="newlinkcat" type="input" id="newlinkcat" size="50" maxlength="200" value="<?php echo $v['newlinkcat']; ?>" /></td>    
            </tr>
       </table>
        <div class="submit">
          <input name="Submit" type="submit" value="Create Feed" class="button-primary" />
        </div>
       </form> 
    </div>    

    <?php
}

function bwc_do_news_create($v,$feedtype = true){
    //Create a Google news feed from the keywords 
    //$v is an array with the name, keywords and category of the link
    //Returns an error as a string or a numeric link id
    
    //Get the keywords
    $newsterm = urlencode($v['keywords']); 

    //Build the rss string
    if ($feedtype) {
        $newsfeed = 'http://news.google.com/news?hl=en&gl=us&q='.$newsterm.'&um=1&ie=UTF-8&output=rss'; //Google news feed
        $linkurl = 'http://news.google.com/';
    } else {
        $newsfeed = 'http://search.twitter.com/search.rss?q='.$newsterm;  //twitter search string
        $linkurl = 'http://search.twitter.com/';
    }
    $current_user = wp_get_current_user();  //Owner of this link
    //Create the new Link Record
    $linkdata = array(
 	"link_url"		=> $linkurl, // varchar, the URL the link points to
	"link_name"		=> $v['aname'], // varchar, the title of the link
	"link_visible"		=> 'Y', // varchar, Y means visible, anything else means not
	"link_owner"		=> $current_user->ID, // integer, a user ID
	"link_rss"		=> $newsfeed, // varchar, a URL of an associated RSS feed
	"link_category"		=> $v['link_category'] // int, the term ID of the link category. 
    );
    $linkval = wp_insert_link( $linkdata, true );
    if (is_wp_error($linkval)){
        return $linkval->get_error_message();
    }
    return $linkval;
}


?>